package com.rzhkj.box.ctrl;

import com.alibaba.fastjson.JSON;
import com.rzhkj.box.entity.Box;
import com.rzhkj.box.entity.BoxFile;
import com.rzhkj.box.service.BoxSV;
import com.rzhkj.box.service.DocSV;
import com.rzhkj.core.base.BaseCtrl;
import com.rzhkj.core.base.JwtToken;
import com.rzhkj.core.common.Constants;
import com.rzhkj.core.entity.BeanRet;
import com.rzhkj.core.exceptions.BaseException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件上传控制器
 */
@Controller
@RequestMapping("/base64")
@Api(value = "base64文件上传", description = "base64文件上传")
@Slf4j
public class Base64UploadCtrl extends BaseCtrl {

    @Resource
    private DocSV docSV;
    @Resource
    private BoxSV boxSV;


//    /**
//     * 上传文件 仅支持base64的编码上传文档方式
//     *
//     * @return BeanRet
//     */
//    @ApiOperation(value = "上传文件 仅支持base64的编码上传文档方式", notes = "上传文件 仅支持base64的编码上传文档方式")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "notificationUrl", value = "回调通知地址", required = true, paramType = "query"),
//            @ApiImplicitParam(name = "suffix", value = "文件后缀", required = true, paramType = "query"),
//            @ApiImplicitParam(name = "file", value = "文件", required = true, paramType = "query")
//    })
//    @PostMapping("/doc")
//    @ResponseBody
//    public BeanRet base64Doc(String notificationUrl, String suffix, String file, @ApiIgnore HttpServletRequest request) throws Exception {
//        Assert.hasText(notificationUrl, BaseException.BaseExceptionEnum.Empty_Param.toString());
//        Assert.hasText(file, BaseException.BaseExceptionEnum.Empty_Param.toString());
//        Assert.hasText(suffix, BaseException.BaseExceptionEnum.Empty_Param.toString());
//
//        String boxCode = (String) request.getAttribute(Constants.BoxCode.val.toString());
//        Assert.hasText(boxCode, BaseException.BaseExceptionEnum.Empty_Param.toString());
//
//        byte[] bytes = Base64Utils.decodeFromString(file);
//        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
//
//        boolean flag = docSV.uploadDoc(boxCode, in, suffix, request.getContentLengthLong(), notificationUrl);
//        return BeanRet.create(flag, "");
//    }


    /***
     * 上传文件 仅支持base64的编码上传图片方式
     * Header:
     * mybox-api-key:"apikey"
     *
     * Body:
     * JWT token
     * xxxx.xxxx.xxxxx
     * 解密后如下：
     *[{
     *  "isCache":"True/False 可选",
     *  "isCover":"True/False 可选",
     *  "size":520,
     *  "mediaType":"JPG",
     *  "file":"base64 code",
     *  "namespace":"路径空间 可选",
     *  "customFileName":"自定义名称 可选",
     *  "compressType":"压缩类型 可选",
     *  "notifyUrl":"回调通知路径 可选",
     *  "notifyData":"回调传递数据 可选",
     *  "notifyContentType":"回传数据类型:Content-Type 可选"
     *}]
     *
     * 1.获取密文，并解密获得apikey，利用apikey判断是否有权限上传
     * 2.解密的数据进行对象转化，并进行上传
     *
     * @return BeanRet
     */
    @ApiOperation(value = "上传文件 仅支持base64的编码上传图片方式", notes = "上传文件 仅支持base64的编码上传图片方式")
    @PostMapping("/pic")
    @ResponseBody
    public BeanRet base64Pic(@RequestBody String data, HttpServletRequest request) {
        //1.获取密文，并解密获得apikey，利用apikey判断是否有权限上传
        String apiKey = request.getHeader(Constants.ApiKey.val.toString());//从header中获取apiKey
        Assert.hasText(apiKey, BaseException.BaseExceptionEnum.Ilegal_Param.name());
        Map<String, Object> param = new HashMap<>();
        param.put("apiKey", apiKey);
        Box box = boxSV.load(param);
        if (box == null) {
            return BeanRet.create();
        }
        Map<String, String> dataMap = JSON.parseObject(data, Map.class);
        if (!dataMap.containsKey("data")) {
            return BeanRet.create();
        }
        JwtToken jwtToken = new JwtToken()
                .secret(box.getApiSecret())
                .token(dataMap.get("data"));

        boolean verify = jwtToken.verifier();
        if (!verify) {
            return BeanRet.create();
        }


        //2.解密的数据进行对象转化，并进行上传
        String json = jwtToken.getTokenValue(Constants.Content.val.toString());
        if (json == null) {
            return BeanRet.create();
        }
        List<BoxFile> boxFiles = JSON.parseArray(json, BoxFile.class);
        boolean flag = docSV.uploadBase64Pic(boxFiles, box.getCode());

        return BeanRet.create(flag, "");
    }


}
